
package com.safebox.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.safebox.R;
import com.safebox.database.DatabaseHandler;
import com.safebox.database.DatabaseHelper;
import com.safebox.security.DataSecurity;
import com.safebox.utils.DialogUtils;

public class LoginActivity extends Activity {
    public static final String TAG = "=LoginActivity=";

    private EditText mUsername;

    private EditText mPassword;

    private LoginTask mLoginTask;

    
    
    public static int EXIT_APPLICATION = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_login);

       

        mUsername = (EditText)findViewById(R.id.edit_username);
        mPassword = (EditText)findViewById(R.id.edit_password);

        findViewById(R.id.button_login).setOnClickListener(mLoginButtonOnClickListener);

        findViewById(R.id.button_register).setOnClickListener(mRegisterButtonOnClickListener);

        String username = getIntent().getStringExtra("username");
        if (!TextUtils.isEmpty(username)) {
            mUsername.setText(username);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        int flag = getIntent().getIntExtra("exit", 0);
        if (flag == EXIT_APPLICATION) {
            finish();
            System.exit(0);
        }
        
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int flag = intent.getIntExtra("exit", 0);
        if (flag == EXIT_APPLICATION) {
            finish();
            System.exit(0);
        }
        
    }

   

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.str_exit_prompt)
                .setPositiveButton(R.string.str_yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        System.exit(0);

                    }
                }).setNegativeButton(R.string.str_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }
                }).create().show();
    }

    private OnClickListener mLoginButtonOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            String username = mUsername.getText().toString().trim();
            String password = mPassword.getText().toString();

            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                Log.i(TAG, "show login failed dialog.");
                DialogUtils.showFailedDialog(LoginActivity.this,
                        getResources().getString(R.string.str_login_error), getResources()
                                .getString(R.string.str_login_error_empty));
            } else {
                mLoginTask = new LoginTask();
                mLoginTask.execute(username, password);
            }
        }
    };

    private OnClickListener mRegisterButtonOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);

        }
    };

    private class LoginTask extends AsyncTask<String, Void, Integer> {

        private static final int SUCCESS = 0;

        private static final int USERNAME_ERROR = 1;

        private static final int PASSWORD_ERROR = 2;

        private static final int ERROR = 3;

        private int user_id;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogUtils.showProgressBarDialog(LoginActivity.this,
                    getResources().getString(R.string.str_login_in_progress));

            DialogUtils.mProgressDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mLoginTask != null) {
                        mLoginTask.cancel(true);
                    }
                }
            });
        }

        @Override
        protected Integer doInBackground(String... params) {
            String username = params[0];
            String password = null;
            try {
                password = DataSecurity.md5(params[1]);
            } catch (Exception ex) {
                Log.e(TAG, "DataSecurity ERROR:" + ex.toString());
            }

            String[] columns = new String[] {
                    DatabaseHelper.AccountsColumns.ACCOUNT_ID,
                    DatabaseHelper.AccountsColumns.PASSWORD
            };
            String select = DatabaseHelper.AccountsColumns.USERNAME + "='" + username + "'";

            Cursor cur = DatabaseHandler.getInstance(LoginActivity.this).query(
                    DatabaseHelper.Tables.ACCOUNTS, columns, select, null, null, null, null);

            if (cur.getCount() == 0) {
                cur.close();
                return USERNAME_ERROR;
            }
            if (cur.moveToFirst() && cur.getCount() == 1) {
                String lPwd = cur.getString(cur
                        .getColumnIndex(DatabaseHelper.AccountsColumns.PASSWORD));
                user_id = cur.getInt(cur.getColumnIndex(DatabaseHelper.AccountsColumns.ACCOUNT_ID));
                cur.close();

                if (password.equals(lPwd)) {
                    return SUCCESS;
                }
                return PASSWORD_ERROR;
            }
            cur.close();
            return ERROR;
        }

        @Override
        protected void onPostExecute(Integer result) {
            DialogUtils.dismissProgressBar();
            Log.i(TAG, "result:" + result);
            switch (result) {
                case SUCCESS:

                    Intent intent = new Intent(LoginActivity.this, InfoListActivity.class);
                    intent.putExtra("userid", user_id);
                    startActivity(intent);

                    break;
                case USERNAME_ERROR:

                    DialogUtils.showFailedDialog(LoginActivity.this,
                            getResources().getString(R.string.str_login_error), getResources()
                                    .getString(R.string.str_login_error_username));
                    break;
                case PASSWORD_ERROR:

                    DialogUtils.showFailedDialog(LoginActivity.this,
                            getResources().getString(R.string.str_login_error), getResources()
                                    .getString(R.string.str_login_error_password));
                    break;
                default:

                    DialogUtils.showFailedDialog(LoginActivity.this,
                            getResources().getString(R.string.str_login_error), getResources()
                                    .getString(R.string.str_login_error));
                    break;
            }

        }

    }

}
